<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Application\Model\Category;
use Admin\Form\MenuForm;
use Admin\Form\NewsForm;
use Application\Model\vn3dUtil;
use Zend\Authentication\AuthenticationService;
use Application\Model\UsersTable;
use Application\Entity\User;
use Application\Model\Users;
class UserController extends AbstractActionController
{

    private $authService;

    private $usersTable;

    public function getUsersTable()
    {
        if (! $this->usersTable) {
            $sm = $this->getServiceLocator();
            $this->usersTable = $sm->get('Application\Model\UsersTable');
        }
        return $this->usersTable;
    }

    public function indexAction()
    {
        $this->layout("layout/login");
        $this->authService = $this->getServiceLocator()->get("Zend\Authentication\AuthenticationService");
        if ($this->authService->getStorage()
            ->getSessionManager()
            ->getSaveHandler()
            ->read($this->authService->getStorage()
            ->getSessionId())) {
            // redirect to success controller...
            return $this->redirect()->toRoute('category');
        }

        $form = $this->getServiceLocator()
            ->get('FormElementManager')
            ->get('Admin\Form\LoginForm');
        $viewModel = new ViewModel();

        // initialize error...
        $viewModel->setVariable('error', '');
        // authentication block...
        $this->authenticate($form, $viewModel);

        $viewModel->setVariable('form', $form);
        return $viewModel;
    }

    /**
     * this function called by indexAction to reduce complexity of function
     */
    protected function authenticate($form, $viewModel)
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $dataform = $form->getData();

                $this->authService = $this->getServiceLocator()->get("Zend\Authentication\AuthenticationService");
                $this->authService->getAdapter()
                    ->setIdentity($dataform['username'])
                    ->setCredential($dataform['password']);
                $result = $this->authService->authenticate();
                if ($result->isValid()) {
                    // authentication success
                    $resultRow = $this->authService->getAdapter()->getResultRowObject();

                    $this->authService->getStorage()->write(array(
                        'id' => $resultRow->id,
                        'username' => $dataform['username'],
                        'ip_address' => $this->getRequest()
                            ->getServer('REMOTE_ADDR'),
                        'user_agent' => $request->getServer('HTTP_USER_AGENT')
                    ));

                    return $this->redirect()->toRoute('category', array(
                        'action' => 'index'
                    ));
                    ;
                } else {
                    $viewModel->setVariable('error', 'Login Error');
                }
            }
        }
    }

    /**
     * this function called by indexAction to reduce complexity of function
     */
    protected function changePass($form, $viewModel)
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $dataform = $form->getData();
               if(  $dataform["new-password"]!=
                    $dataform["new-password-confirm"]){

                   $viewModel->setVariable('error',"Mật khẩu không trùng nhau");
               }else {
                $form->setData($request->getPost());
                if ($form->isValid()) {

                    $admin=$this->getUsersTable()->getAdmin();

// var_dump($admin);
                    $admin->password=$dataform["new-password"];

                    $this->getUsersTable()->saveUsers($admin);
                    return $this->redirect()->toRoute('user', array(
                        'action' => 'logout'
                    ));

                } else {
                    $viewModel->setVariable('error', 'Change pass Error');
                }
               }
            }
        }
    }

    public function logoutAction()
    {
        $this->authService = $this->getServiceLocator()->get("Zend\Authentication\AuthenticationService");
        $this->authService->getStorage()->clear();
        return $this->redirect()->toRoute('user', array(
            "action" => "index"
        ));
    }

    public function changePassAction()
    {
//         $this->layout("layout/admin");
        $this->authService = $this->getServiceLocator()->get("Zend\Authentication\AuthenticationService");
        if (! ($this->authService->getStorage()
            ->getSessionManager()
            ->getSaveHandler()
            ->read($this->authService->getStorage()
            ->getSessionId()))) {
            // redirect to success controller...
            return $this->redirect()->toRoute('user', array(
                "action" => "index"
            ));
        }

        $form = $this->getServiceLocator()
            ->get('FormElementManager')
            ->get('Admin\Form\ChangePassword');
        $viewModel = new ViewModel();

        // initialize error...
        $viewModel->setVariable('error', '');
        // authentication block...
        $this->changePass($form, $viewModel);

        $viewModel->setVariable('form', $form);

        $this->layout("/layout/login");
//         $controller->forward()->dispatch("Application\Controller\Store", array(
//         		'action' => 'search',
//         		'controller' => 'Application\Controller\Store'
//         ));
        return $viewModel;
    }
}
